package com.neusoft.elmboot.service.Impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.mapper.CartMapper;
import com.neusoft.elmboot.mapper.FoodMapper;
import com.neusoft.elmboot.mapper.OrderDetailetMapper;
import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.po.Cart;
import com.neusoft.elmboot.po.Food;
import com.neusoft.elmboot.po.OrderDetailet;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.service.OrdersService;
import com.neusoft.elmboot.util.CommonUtil;

@Service
public class OrdersServiceImpl implements OrdersService{

	@Autowired
	private CartMapper cartMapper;
	
	@Autowired
	private OrdersMapper ordersMapper;
	
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
	
	@Autowired
	private FoodMapper foodMapper;
	
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ)
	public int createOrders(Orders orders) {

		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);

		for(Cart c : cartList) {
			Food food = foodMapper.getFoodById(c.getFoodId());
			food.setFoodQuantity(c.getQuantity());
			int result = foodMapper.buyFood(food);
			if(result == 0) {
				return 0; 
			}
		}
		
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();
		
		List<OrderDetailet> list = new ArrayList<>();
		for(Cart c : cartList) {
			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodId(c.getFoodId());
			od.setQuantity(c.getQuantity());
			Double p = 0.0;
			od.setOldPrice(p);
			list.add(od);
		}
		orderDetailetMapper.saveOrderDetailetBatch(list);

		cartMapper.removeCart(cart);

		CreditTrans creditTrans = new CreditTrans(); 
		creditTrans.setUserId(orders.getUserId());
		creditTrans.setEventId(orderId);
		creditTrans.setCredit(orders.getOrderTotal().intValue());
		creditService.addCredit(creditTrans);
		
		
		return orderId;
	}
	
	@Override
	public Orders getOrdersById(Integer oderId) {
		return ordersMapper.getOrdersById(oderId);
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}
	
	@Override
	public int updateOrderStateByOrderId(Integer orderId) {
		return ordersMapper.updateOrderStateByOrderId(orderId);
	}
	
	@Override
	public List<Orders> listOrdersByBusinessId(Integer businessId){
		return ordersMapper.listOrdersByBusinessId(businessId);
	}
}